package com.example.token.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@Component
public class JwtUtil {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private final static String signature = "admin";

    public String createToken() throws JsonProcessingException {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                // header
                .setHeaderParam("type", "JWT")
                .setHeaderParam("alg", "HS256")
                // payload
                .claim("username", "zhang")
                .claim("role", "admin")
                .setSubject("admin-test")
                .setId(UUID.randomUUID().toString())
                // signature
                .signWith(SignatureAlgorithm.HS256, signature) //设置签名算法
                .compact(); //拿到一个字符串类型的返回值

        return jwtToken;
    }

    public boolean validateToken(String token) {
        try {
            return Boolean.TRUE.equals(redisTemplate.hasKey(token));
        } catch (Exception e) {
            System.out.println(e);
            log.error("无效token");
            return false;
        }
    }

}
